package com.unohacha.qqj.fzdr.main;


import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.qpg.widget.common.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.SupplyMatchModel;
import com.unohacha.qqj.fzdr.bean.homebean.MoreDataBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 查看更多信息
 */
public class LookMoreInfoActivity extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    
    private int page = 1;
    private int member_id;//用户Id
    private int one_pid;//一级分类Id
    private int supply_cate_id;//二级分类Id
    private int typeid;//供求分类 1-供应；2-需求【人员招聘，人员求职都传“1”】
    private BaseRVAdapter mBaseAdapter;
    private List<MoreDataBean.DataBeanX.DataBean> dataBeanList = new ArrayList<>();

    //从匹配页面进入
    private int matchToLook = 0;
    private String order;
    private String ptype;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_look_more_info;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.more_info));
        commonRightImage.setVisibility(View.GONE);
        commonRightText.setVisibility(View.INVISIBLE);
        initRefreshData();
    }

    private void initRefreshData() {
        
        if (null != getIntent()){
            member_id = getIntent().getIntExtra("member_id",0);
            one_pid = getIntent().getIntExtra("one_pid",0);
            supply_cate_id = getIntent().getIntExtra("supply_cate_id",0);
            typeid = getIntent().getIntExtra("typeid",0);
            matchToLook = getIntent().getIntExtra("matchToLook",0);
            order = getIntent().getStringExtra("order");
            ptype = getIntent().getStringExtra("ptype");
        }
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        if (matchToLook == 10000) //从匹配页面进入
            getDefaultFind();
        else
            getMoreData(member_id,one_pid,supply_cate_id,typeid);
    }
    
    @OnClick({R.id.common_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
        }
    }

    private void getDefaultFind() {
        Map<String, Object> stringMap = new HashMap<>();
        stringMap.put("token", Prefer.getInstance().getToken());
        stringMap.put("order",order);
        stringMap.put("ptype",ptype);
        stringMap.put("more","1");
        stringMap.put("page",page);

        XUtil.Post(UrlConfig.SUPPLY_MATCHING, stringMap, new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadmore();
                }

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        MoreDataBean moreDataBean = gson.fromJson(result,MoreDataBean.class);
                        if (null != moreDataBean){
                            if (page == 1){
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                if (null != dataBeanList){
                                    dataBeanList.clear();
                                }
                                dataBeanList.addAll(moreDataBean.getData().getData());
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                            setMyBaseAdapter();
                        }
                    }else if ("100".equals(jsonObject.optString("code"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            if (null != dataBeanList) {
                                dataBeanList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }



                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadmore();
                }
            }
        });
    }
    
    private void getMoreData(int member_id,int one_pid,int supply_cate_id,int typeid){
        showLoading();
        Map<String,Object> params = new HashMap<>();
        params.put("member_id",member_id);
        params.put("one_pid",one_pid);
        params.put("supply_cate_id",supply_cate_id);
        params.put("typeid",typeid);
        params.put("address_id", Prefer.obtainReLocation(this));
        params.put("page",page);
        XUtil.Post(UrlConfig.SUPPLY_LIST_MORE,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadmore();
                }

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))){
                        Gson gson = new Gson();
                        MoreDataBean moreDataBean = gson.fromJson(result,MoreDataBean.class);
                        if (null != moreDataBean){
                            if (page == 1){
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                if (null != dataBeanList){
                                    dataBeanList.clear();
                                }
                                dataBeanList.addAll(moreDataBean.getData().getData());
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                            setMyBaseAdapter();
                        }
                    }else if ("100".equals(jsonObject.optString("code"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            if (null != dataBeanList) {
                                dataBeanList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                    
                  
                    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadmore();
                }
            }
        });
    }
    
    private void setMyBaseAdapter(){
        if (null != dataBeanList) {
            mBaseAdapter = new BaseRVAdapter(this, dataBeanList) {
                @Override
                public int getLayoutId(int viewType) {
                    return R.layout.item_find_need_or_supply2;
                }

                @Override
                public void onBind(BaseViewHolder holder, final int position) {
                    final int tagPosition = position;
                    ImageView store_logo_iv = holder.getImageView(R.id.store_logo_iv);//头像
                    TextView store_name_tv = holder.getTextView(R.id.store_name_tv);//名字
                    TextView store_report_content = holder.getTextView(R.id.store_report_content);//发表的标题
                    TextView report_content = holder.getTextView(R.id.report_content);//发表的内容
                    TextView report_time_tv = holder.getTextView(R.id.report_time_tv);//发表的时间
                    TextView look_num_tv = holder.getTextView(R.id.look_num_tv);//浏览的数量
                    TextView comment_num_tv = holder.getTextView(R.id.comment_num_tv);//评论的数量
                    TextView collect_num_tv = holder.getTextView(R.id.collect_num_tv);//收藏的数量
                    TextView get_message_tv = holder.getTextView(R.id.get_message_tv);//获取信息
                    RelativeLayout look_life_more = holder.getRelayout(R.id.look_life_more);//查看更多

                    look_num_tv.setText(dataBeanList.get(position).getHits() + " 浏览");
                    comment_num_tv.setText(dataBeanList.get(position).getCommon_nums() + " 评论");
                    collect_num_tv.setText(dataBeanList.get(position).getCollection_count() + " 收藏");
                    Glide.with(LookMoreInfoActivity.this).load(dataBeanList.get(position).getMember_thumb()).error(R.drawable.ic_default_photo).into(store_logo_iv);
                    store_name_tv.setText(dataBeanList.get(position).getMember_no());
                    store_report_content.setText(dataBeanList.get(position).getTitle());
                    report_content.setText(dataBeanList.get(position).getContent());
                    report_time_tv.setText(dataBeanList.get(position).getCreate_time());
                    get_message_tv.setVisibility(View.GONE);
                    look_life_more.setVisibility(View.GONE);


                    //九宫格展示
                    ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                    List<String> imageDetails = dataBeanList.get(position).getList_pic();
                    if (imageDetails != null) {
                        for (String imageDetail : imageDetails) {
                            ImageInfo info = new ImageInfo();
                            info.setThumbnailUrl(imageDetail);
                            info.setBigImageUrl(imageDetail);
                            imageInfo.add(info);
                        }
                    }

                    NineGridView mRecyclerView = holder.getView(R.id.mRecyclerView);//图片的列表 3 列
                    mRecyclerView.setSingleImageSize(500);
                    mRecyclerView.setAdapter(new NineGridViewClickAdapter(mContext, imageInfo));
//                    mRecyclerView.setLayoutManager(new GridLayoutManager(LookMoreInfoActivity.this, 3, GridLayoutManager.VERTICAL, false));
//                    BaseRVAdapter mPicAdapter = new BaseRVAdapter(LookMoreInfoActivity.this, dataBeanList.get(position).getList_pic()) {
//                        @Override
//                        public int getLayoutId(int viewType) {
//                            return R.layout.item_find_pic;
//                        }
//
//                        @Override
//                        public void onBind(BaseViewHolder holder, final int position) {
//                            ImageView find_pic_iv = holder.getImageView(R.id.find_pic_iv);
//                            Glide.with(LookMoreInfoActivity.this).load(dataBeanList.get(tagPosition).getList_pic().get(position)).into(find_pic_iv);
//                            find_pic_iv.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    //点击查看大图
//                                    Intent intent = new Intent(LookMoreInfoActivity.this, LookBigPicActivity.class);
//                                    intent.putExtra("imgUrl", dataBeanList.get(tagPosition).getList_pic_compress().get(position));
//                                    intent.putExtra("listData", dataBeanList.get(tagPosition));
//                                    intent.putExtra("type", "2");
//                                    startActivity(intent);
//                                }
//                            });
//                        }
//
//                    };
//                    mRecyclerView.setAdapter(mPicAdapter);
//                    mPicAdapter.notifyDataSetChanged();
                }
            };
        }
        carListRecycler.setAdapter(mBaseAdapter);

        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
//                if (homeType == 4) {
                //TalkDetailActivity2
                String address_id = Prefer.getInstance().obtainReLocation(LookMoreInfoActivity.this);
                if (address_id.length() == 0) {
                    ToastUtils.showT("未选择地区");
                    return;
                }
                String id = dataBeanList.get(position).getId() + "";
//                    System.out.println("--------->id=" + id + "\n----->supply_cate_id=" + supply_cate_id + "\n---------->address_id=" + address_id);
                Intent intent = new Intent(LookMoreInfoActivity.this, FindDetailActivity2.class);
                intent.putExtra("typeid", dataBeanList.get(position).getSupply_cate_id());
                intent.putExtra("address_id", address_id);
                intent.putExtra("id", Integer.valueOf(id));
                startActivity(intent);

//                }
            }
        });
    }
    
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page ++;
        if (matchToLook == 10000)
            getDefaultFind();
        else
            getMoreData(member_id,one_pid,supply_cate_id,typeid);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        if (matchToLook == 10000)
            getDefaultFind();
        else
            getMoreData(member_id,one_pid,supply_cate_id,typeid);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
